package com.dashen.sso.resource.config.security;

import com.dashen.sso.common.user.DaShenUserDetails;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * @author Barry Wang
 */
public class DaShenUserDetailsServiceImpl implements UserDetailsService {

    private final static Set<DaShenUserDetails> USERS = new HashSet<DaShenUserDetails>();

    static {
        USERS.add(new DaShenUserDetails(1, "user1", encode("12345")));
        USERS.add(new DaShenUserDetails(2, "user2", encode("12345")));
        USERS.add(new DaShenUserDetails(3, "user3", encode("12345")));
        USERS.add(new DaShenUserDetails(4, "user4", encode("12345")));
    }

    public static String encode(String pass){
        return PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(pass);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Optional<DaShenUserDetails> user = USERS.stream()
                .filter((u) -> u.getUsername().equals(username))
                .findFirst();

        if(!user.isPresent()) {
            throw new UsernameNotFoundException("there's no user founded!");
        }
        else {
            return user.get();
        }
    }


}
